<!--
- File:    选择城市.
-->
<template>
  <div>
    <div class=" xd top_bg">
      <div class="list_search">
        <form action="" @submit="search">
          <input type="text" autocomplete="off" v-model="keyword" placeholder="请输入城市名"><i class="iconfont icon-search" @click="search"></i>
        </form>
      </div>
      <div class="cancel" @click="cancleSearch">取消</div>
    </div>
    <div v-show="mode == 'search'">
      <div class="select-city-item" @click="selectCity(city)" v-for="city in searchResultList.data">
        {{city.name}}
      </div>
      <p style="width: 100%; text-align: center; padding: 50px 0; font-size: 14px; color: #999;" v-show="searchResultList.requested && searchResultList.data.length <= 0">
        暂不支持该城市~
      </p>
    </div>
    <div v-show="mode == 'select'">
      <mt-index-list>
        <div class="mint-indexsection-index">定位城市</div>
        <div class="select-city-item" style="border: none" @click="selectCity(location)">
         <span class="hot-city-item">
           {{location.name}}
          </span>
        </div>
        <div class="mint-indexsection-index">热门城市</div>
        <div class="hot-city-wrap">
          <span class="hot-city-item" v-for="item in hotCity" @click="selectCity(item)">
            {{item.name}}
          </span>
        </div>
        <mt-index-section :index="item.alphabet" v-for="(item, index) in cityList" :key="index">
          <div class="select-city-item" v-for="(city, index2) in item.list" @click="selectCity(city)">
            <!--<mt-cell :title="city.name"></mt-cell>-->
            {{city.name}}
          </div>
        </mt-index-section>
      </mt-index-list>
    </div>
  </div>
</template>
<script>
  import mkPy from '../../assets/dep/mkPy'
  import {city} from '../../assets/dep/city-data'
  import {IndexList, IndexSection, Cell} from 'mint-ui'
  export default{
    data() {
      return {
        keyword: '',
        mode: 'select', // search: 搜索模式，select： 选择模式
        cityList: [],
        location: {code: '', name: '定位中...'},
        searchResultList: {requested: false, loading: false, data: []},
        hotCity: [{
          'code': '36',
          'name': '北京市',
          'parentId': '1'
        }, {
          'code': '39',
          'name': '上海市',
          'parentId': '9'
        }, {
          'code': '289',
          'name': '广州市',
          'parentId': '19'
        }, {
          'code': '291',
          'name': '深圳市',
          'parentId': '19'
        }, {
          'code': '204',
          'name': '厦门市',
          'parentId': '13'
        }, {
          'code': '203',
          'name': '福州市',
          'parentId': '13'
        }]
      }
    },
    components: {
      'mtIndexList': IndexList,
      'mtIndexSection': IndexSection,
      'mtCell': Cell
    },
    created() {
      this.getCityList()
    },
    mounted() {
      this.getLocation()
    },
    methods: {
      back() {
        this.$router.go(-1)
      },
      search(e) {
        e.preventDefault()
        if (this.keyword.trim() == '') {
          return
        }
        this.searchResultList = {requested: false, loading: false, data: []}
        this.searchResultList.loading = true
        this.mode = 'search'
        for (let i = 0; i < city.length; i++) {
          if (city[i].name.indexOf(this.keyword) != -1) {
            this.searchResultList.data.push(city[i])
          }
        }
        this.searchResultList.requested = true
        this.searchResultList.loading = false
      },
      cancleSearch() {
        this.keyword = ''
        this.mode = 'select'
        this.searchResultList = {requested: false, loading: false, data: []}
      },
      getLocation() {
        this.$utils.getLocal().then(data => {
          let code = this.getCityCode(data.city)
          this.location = {code: code, name: data.city}
          console.log('location:', this.location)
        }).catch(e => {
          this.location = {code: '', name: '定位失败'}
          console.error('获取定位失败', e)
        })
      },
      getCityList() {
        this.cityList = this.groupByAlphabet(city)
      },
      getCityCode(name) {
        for (let i = 0; i < city.length; i++) {
          if (city[i].name.indexOf(name) != -1) {
            return city[i].code
          }
        }
        return ''
      },
      // 处理多音字
      dealDyz(str) {
        let dyzList = [{name: '重庆', Alphabet: 'C'},
          {name: '重庆市', Alphabet: 'C'},
          {name: '屯门区', Alphabet: 'T'},
          {name: '佛山市', Alphabet: 'F'},
          {name: '澄迈县', Alphabet: 'C'}
        ]
        for (let i = 0; i < dyzList.length; i++) {
          if (dyzList[i].name == str) {
            return dyzList[i].Alphabet
          }
        }
        return null
      },
      // 城市列表按其首字母分组并排序
      groupByAlphabet(cityList) {
        var alphabetList = []
        var cityListResult = []
        cityList.map((value, index) => {
          var itemAlphabet
          let aTmp = this.dealDyz(value.name)
          if (aTmp) {
            itemAlphabet = aTmp
          } else {
            itemAlphabet = mkPy(value.name[0])[0].charAt(0)
          }
          if (alphabetList.indexOf(itemAlphabet) == -1) {
            alphabetList.push(itemAlphabet)
            var resultItem = {}
            resultItem.alphabet = itemAlphabet
            resultItem.list = []
            resultItem.list.push(value)
            cityListResult.push(resultItem)
          } else {
            for (var i = 0, l = cityListResult.length; i < l; i++) {
              if (cityListResult[i].alphabet === itemAlphabet) {
                cityListResult[i].list.push(value)
              }
            }
          }
        })
        // 根据首字母排序
        cityListResult = cityListResult.sort(function (a, b) {
          if (a.alphabet > b.alphabet) {
            return 1
          }
          return -1
        })
        return cityListResult
      },
      async selectCity(city) {
        if (city.code == '') {
          return
        }
        this.$storage.setLocation(city)
        let isExistStore = await this.isExistStore(city.code)
        if (isExistStore) {
          this.$router.push({name: 'store-list'})
        } else {
          this.$storage.setStore(this.$config.storeId)
          this.$router.push({name: 'home'})
        }
      },
      isExistStore(cityId) { // 该城市是否存在店铺
        return new Promise((resolve, reject) => {
          this.$request.getStoreList(cityId, 1, 1).then(data => {
            if (data.length > 0) {
              resolve(true)
            } else {
              resolve(false)
            }
          }).catch(e => {
            console.error('获取城市的店铺失败', e)
            resolve(false)
          })
        })
      }
    }
  }
</script>
<style>
  .select-city-item {
    padding: 10px;
    background-color: #fff;
    border-top: 1px solid lightgray;
    font-size: 14px;
  }

  .hot-city-wrap {
    padding: 10px;
    background: #fff;
    /*border-top: 1px solid lightgray;*/
  }

  .hot-city-item {
    display: inline-block;
    padding: 5px 10px;
    margin: 0 10px 10px 0;
    background: #efeff4;
  }

  .mint-indexsection-index {
    /*border-bottom: 1px solid lightgray;*/
    background-color: #efeff4;
    padding: 5px 10px;
  }
</style>